package com.comac.tasks.manager.app.filter;

import com.alibaba.cola.dto.SingleResponse;
import com.xxl.sso.core.util.ResponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @Description feign api鉴权
 * @Author lihao
 * @Date 2022/1/14 19:07
 */
@Slf4j
public class FeignAuthFilter implements Filter {

    @Autowired
    private FeignAuthProperties feignAuthProperties;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    /**
     * 校验权限
     *
     * @return
     */
    private boolean checkPermissions(String appCode, String appAccessKey) {
        if (StringUtils.isBlank(appCode)) {
            log.warn("AppCode is empty!");
            return false;
        }
        if(StringUtils.isBlank(appAccessKey)) {
            log.warn("AppAccessKey is empty!");
            return false;
        }
        Map<String, String> apps = feignAuthProperties.getApps();
        if(CollectionUtils.isEmpty(apps)) {
            log.warn("Application {} has no permission config！", appCode);
            return false;
        }
        if(!apps.get(appCode).equals(appAccessKey)) {
            log.warn("Application {} has error appAccessKey！", appCode);
            return false;
        }
        return true;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        log.info("FeignAuthFilter.doFilter begin ");
        if(request.getRequestURI().contains("/findFrrBacklog")||request.getRequestURI().contains("/delete")){
            filterChain.doFilter(servletRequest, servletResponse);
        }else{
            if (feignAuthProperties.isEnable()) {
                HttpServletResponse response = (HttpServletResponse) servletResponse;
                String appCode = request.getHeader("app-code");
                String appAccessKey = request.getHeader("app-access-key");
                if (!checkPermissions(appCode, appAccessKey)) {
                    ResponseUtils.writeResponse(response, SingleResponse.buildFailure("-1", "Application has no permission！"));
                    return;
                }
            } else {
                log.warn("Permission not opened！");
            }
            filterChain.doFilter(servletRequest, servletResponse);
            log.info("FeignAuthFilter.doFilter end ");
        }

    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
